use std::time::{SystemTime, UNIX_EPOCH};



pub fn current_timestamp() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()
}

pub fn new_buf(size: usize) -> Box<[u8]> {
    let mut buf = Vec::with_capacity(size);
    unsafe { buf.set_len(size); }
    buf.into_boxed_slice()
}

const HEX_LIST: [u8; 16] = [
    b'0', b'1', b'2', b'3',
    b'4', b'5', b'6', b'7',
    b'8', b'9', b'a', b'b',
    b'c', b'd', b'e', b'f'
];

pub fn bytes_to_hex(buf: &[u8]) -> String {
    let mut s = Vec::with_capacity(buf.len() * 2);
    for b in buf {
        let v = *b;
        let h = (v >> 4) as usize;
        let l = (v & 0x0F) as usize;
        s.push( HEX_LIST[h] );
        s.push( HEX_LIST[l] );
    }
    unsafe { String::from_utf8_unchecked(s) }
}

const MD5_EXT: &'static str = "bread-ext";

pub fn pwd_md5_enc(pwd: &str) -> String {
    let raw = format!("{}{}", pwd, MD5_EXT);
    let buf = md5::compute(raw);
    bytes_to_hex(&buf.0)
}


pub fn encode_u8(buf: &mut[u8], v: u8) {
    buf[0] = v;
}

pub fn encode_u16(buf: &mut[u8], v: u16) {
    buf[0] = (v >> 8) as u8;
    buf[1] = v as u8;
}

pub fn decode_u8(buf: &[u8]) -> u8 {
    buf[0]
}

pub fn decode_u16(buf: &[u8]) -> u16 {
    ((buf[0] as u16) << 8) + (buf[1] as u16)
}

